<?php
class Catalog_ItemController extends Zend_Controller_Action
{
	public function init()
	{
		// switch output search contecst in XML
		$contextSwitch = $this->_helper->getHelper('contextSwitch');
		$contextSwitch->addActionContext('search', 'xml')->initContext();
	}
	
	// visible catalog element
	public function displayAction() 
	{
		//validation
		$filters = array(
				'id' => array('HtmlEntities', 'StripTags', 'StringTrim')
		);
		
		$validators = array(
				'id' => array('NotEmpty', 'Int')
		);
		
		$input = new Zend_Filter_Input($filters, $validators);
		$input->setData($this->getRequest()->getParams());
		
		if($input->isValid())
		{
			$query = Doctrine_Query::create()
				->from('Zend_Model_Item i')
				->leftJoin('i.Zend_Model_Country c')
				->leftJoin('i.Zend_Model_Grade g')
				->leftJoin('i.Zend_Model_Type t')
				->where('i.RecordID = ?', $input->id)
				->andWhere('i.DisplayStatus = 1')
				->andWhere('i.DisplayUntil >= CURDATE()');

			$res = $query->fetchArray();
			if(count($res) == 1)
			{
				$this->view->item = $res[0];
				$this->view->images->array();
				
				$config = $this->getInvokeArg('bootstrap')->getOption('upload');
				
				foreach (glob("{$config['uploadPath']}/{$this->view->item['RecordID']}_*") as $file)
				{
					$this->view->images[] = basename($file);
				}
				$config = $this->getInvokeArg('bootstrap')->getOption('configs');
				$localConfig = new Zend_Config_Ini($config['localConfigPath']);
				$this->view->seller = $localConfig->user->displaySellerInfo;
			}
			else 
				{
				throw new Zend_Controller_Action_Exception('dont work',404);	
			}
		}
		else 
		{
			throw new Zend_Controller_Action_Exception('invalid $_GET data');
		}
	}
	
	/*
	 * 		CREATE ACTION
	 */
	
	public function createAction()
	{
		// show create form
		$createItemForm = new Inc_Form_ItemCreate();
		$this->view->createItemForm = $createItemForm;
		
		if ($this->getRequest()->isPost())
		{
			if ($createItemForm->isValid($this->getRequest()->getPost()))
			{
				$item = new Zend_Model_Item();
				
				$item->fromArray($createItemForm->getValues());
				$item->RecordDate = date('Y-m-d', mktime());
				$item->DisplayStatus = 0;
				$item->DisplayUntil = null;
				$item->save();
				$id = $item->RecordID;
				
				// for downloaded files
				$config = $this->getInvokeArg('bootstrap')->getOption('uploads');
				$createItemForm->images->setDestination($config['uploadPath']);
				
				$adapter = $createItemForm->images->getTransferAdapter();
				
				for ($x=0; $x < $createItemForm->images->getMultiFile(); $x++)
				{
					$xt = @pathinfo($adapter->getFileName('images_'. $x .'_').PATHINFO_EXTENSION);
					$adapter->clearFilters();
					$adapter->addFilter('Rename', array(
							'target' => sprintf('%d_%d.%s', $id, ($x+1), $xt),
							'overwrite' => true
							));
					
					$adapter->receive('images_'. $x .'_');
				}				

				$fm = $this->_helper->getHelper('flashMessenger');
				$fm->addMessage('Your submission has been accepted as item #'.$id);
				
				// if 'ok' redirect
				$this->_redirect('/catalog/item/success');
			}
		}
	} 
	
	/*
	 * 		SUCCESS ACTION
	 */
	
	public function successAction()
	{
		if ($this->_helper->getHelper('flashMessenger')->getMessages())
		{
			$this->view->message = $this->_helper->getHelper('flashMessenger')->getMessages();
		} 
		else 
		{ 
			$this->_redirect('/');
		}
	}
	
	/*
	 * 		SEARCH ACTION
	 */
	
	public function searchAction()
	{
		/*
		 * 		show search form 
		 */
		$searchForm = new Inc_Form_Search();
		$this->view->searchForm = $searchForm;
		
		if ($searchForm->isValid($this->getRequest()->getParams()))
		{
			$input = $searchForm->getValues();
			
			$query = Doctrine_Query::create()
				->from('Zend_Model_Item i')
				->leftJoin('i.Zend_Model_Country c')
				->leftJoin('i.Zend_Model_Grade g')
				->leftJoin('i.Zend_Model_Type t');
				//->where('i.DisplayStatus = 1');
				//->addWhere('i.DisplayUntil >= CURDATE()');
			
			/*
			 * 		add query form date
			 */
			
			if(!empty($input['y'])) 
			{
				$query->addWhere('i.Year = '.$input['y']);
			}
			if(!empty($input['p']))
			{
				// dont work this addWhere method
				$query->addWhere('? BETWEEN i.SalePriceMin AND i.SalePriceMax', $input['p']);
			}
			if(!empty($input['g'])) 
			{
				$query->addWhere('i.GradeID ='.$input['g']);
			}
			
			// $sql = $query->getSqlQuery();
			
			$resSearch = $query->fetchArray();
			$this->view->resSearch = $resSearch;
			/* $this->view->sql = $sql;
			$this->view->input = $input; */
		}
	}
	
	/*
	 *		SEARCH FULLTEXT INDEX 
	 */
	
	public function searchkeyAction()
	{
		/*
		 * 		show search form
		*/
		$searchKeywordsForm = new Inc_Form_KeywordSearch();
		$this->view->searchKeywordForm = $searchKeywordsForm;
	
		if ($searchKeywordsForm->isValid($this->getRequest()->getParams()))
		{
			$input = $searchKeywordsForm->getValues();
				
			if(!empty($input['key']))
			{
				$config = $this->getInvokeArg('bootstrap')->getOption('indexes');
				$index = Zend_Search_Lucene::open($config['indexPath']);
				$result = $index->find(Zend_Search_Lucene_Search_QueryParser::parse($input['key']));
				$this->view->result = $result;
			}		
		}
	}
}